
#include "bsp.h"

#include "driver/ledc.h"

#define TAG "LIGHT"

#define LEDC_TIMER              LEDC_TIMER_0
#define LEDC_MODE               LEDC_LOW_SPEED_MODE
#define LEDC_OUTPUT_IO          1//CONFIG_LIGHT_PWM_GPIO//(0) // Define the output GPIO
#define LEDC_CHANNEL            LEDC_CHANNEL_0
#define LEDC_DUTY_RES           LEDC_TIMER_13_BIT // Set duty resolution to 13 bits
#define LEDC_DUTY               4095//CONFIG_LIGHT_PWM_DUTY//(4095) // Set duty to 50%. ((2 ** 13) - 1) * 50% = 4095
#define LEDC_FREQUENCY          5000//CONFIG_LIGHT_PWM_FREQUENCY_HZ//(5000) // Frequency in Hertz. Set frequency at 5 kHz



/*******************************************************************************
* 功能描述	: 设置PWM占空比，主要用于控制灯
* 参数一    : duty  pwm占空比（0~100之间）
* 返回参数  : 无
********************************************************************************
*修改日期             修改人          修改备注
*20211116            umi             初始版本
*******************************************************************************/
void Tospo_Ledc_PPM_Set_duty(uint8_t duty)
{
    uint32_t pwm_duty = 0;

    if(duty > 100)
    {
        pwm_duty = 8100;
    }else
    {
        pwm_duty = duty * 81;
    }
    
    ESP_LOGI(TAG,"pwm_duty== %d\n", pwm_duty);
    ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, pwm_duty));
    // Update duty to apply the new value
    ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
}

/*******************************************************************************
* 功能描述	: LED PWM 初始化
* 参数    : 无
* 返回参数  : 无
********************************************************************************
*修改日期             修改人          修改备注
*20211116            umi             初始版本
*******************************************************************************/
void bsp_light_init(void)
{
     // Prepare and then apply the LEDC PWM timer configuration
    ledc_timer_config_t ledc_timer = {
        .speed_mode       = LEDC_MODE,
        .timer_num        = LEDC_TIMER,
        .duty_resolution  = LEDC_DUTY_RES,
        .freq_hz          = LEDC_FREQUENCY,  // Set output frequency at 5 kHz
        .clk_cfg          = LEDC_AUTO_CLK
    };
    ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));

    // Prepare and then apply the LEDC PWM channel configuration
    ledc_channel_config_t ledc_channel = {
        .speed_mode     = LEDC_MODE,
        .channel        = LEDC_CHANNEL,
        .timer_sel      = LEDC_TIMER,
        .intr_type      = LEDC_INTR_DISABLE,
        .gpio_num       = LEDC_OUTPUT_IO, 
        .duty           = 0, // Set duty to 0%
        .hpoint         = 0
    };
    ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));


    Tospo_Ledc_PPM_Set_duty(50);
}

